<script setup lang="ts">
import type { LogTable } from '@/types/log'
import { ref } from 'vue'
import { exportLog } from './api'
import type { AxiosProgressEvent } from 'axios'
import { utils, writeFile } from 'xlsx'
const props = defineProps<{
  cdn: LogTable
  type: 'handle' | 'sign'
  tDict: Map<string, string>
}>()

const Progress = ref(0)
let exportData: LogTable[] = []
function getExportData() {
  exportLog(props.type, props.cdn, (e: AxiosProgressEvent) => {
    if (e.progress != 1) {
      Progress.value = Number((e.progress! * 95).toFixed(2))
    } else {
      setTimeout(() => {
        Progress.value = 100
      }, 500)
    }
  }).then((resp) => {
    exportData = resp.data
  })
}

// 获取进度状态
function getProgressStatus() {
  if (Progress.value == 100) {
    return 'success'
  }
  return 'warning'
}
// 下载数据
function download() {
  let workbook = utils.book_new()
  let data = exportData.map((d) => {
    let ent = Object.entries(d)
    let out: any = {}
    ent.map((d) => {
      out[props.tDict.get(d[0]) || d[0]] = d[1]
    })
    return out
  })
  let sheet = utils.json_to_sheet(data)
  utils.book_append_sheet(workbook, sheet, props.type)
  writeFile(workbook, `${props.type}.xlsx`)
}
</script>
<template>
  <div>
    <el-button class="download-data" @click="getExportData" type="warning">准备数据</el-button>
    <div>
      <span>下载进度: {{ Progress }}%</span>
      <el-progress
        :percentage="Progress"
        :stroke-width="15"
        :status="getProgressStatus()"
        striped
        striped-flow
        :duration="10"
      />
    </div>
    <el-row justify="center">
      <el-col :span="2"
        ><el-button :disabled="Progress != 100" type="primary" @click="download"
          >保存</el-button
        ></el-col
      >
    </el-row>
  </div>
</template>
<style scoped lang="less">
.download-data {
  margin-bottom: 20px;
}

.el-row {
  margin-top: 30px;
}
</style>
